<template>
    <div class="page-container" >
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/login' }">登录</el-breadcrumb-item>
            <el-breadcrumb-item>忘记密码</el-breadcrumb-item>
        </el-breadcrumb>
        
        <div class="main">
            
            <div class="content">
                <div class="goback">
                    <el-button type="primary" icon="el-icon-arrow-left" v-show="active>='1'" @click="()=>{this.active--}/*$router.go(-1)*/">
                        上一步
                    </el-button>
                </div>
                <div class="step">
                    <el-steps :active="active" align-center finish-status="success" >
                        <!-- simple -->
                        <el-step title="确认账号" ></el-step>
                        <el-step title="短信验证" ></el-step>
                        <el-step title="重置密码" ></el-step>
                    </el-steps>
                </div>
                
                <el-divider></el-divider>
                <el-form ref="resetForm" :model="resetForm" :rules="resetFormRules"  label-width="80px" label-position="right">
                    <div v-if="active=='0'" class="stepItem">
                        <el-form-item prop="account" label="账号" @keydown.enter.native.prevent="()=>{}" >
                            <el-input v-model="resetForm.account" type="text" placeholder="请输入你的学号/工号">
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="isLock" v-if="active == '0'" >
                            <slider-verify-code :isLock="islock" v-show="!islock"  @change="checkAcount"></slider-verify-code>
                        </el-form-item>
                        
                        <!-- <div>
                            <SliderVerifyCode :isLock="islock" v-show="!islock"  @change="checkAcount"></SliderVerifyCode>
                        </div> -->
                    </div>
                    <div v-if="active=='1'" class="stepItem">
                            
                            <!-- <div slot="tip" class="el-upload__tip">请输入您账号绑定的手机号</div> -->
                            
                            <el-form-item prop="phone" label="手机号" >
                                <el-input size="normal" type="text" v-model="resetForm.phone" placeholder="请输入您账号绑定的手机号">
                                    <i slot="prefix" class="el-icon-phone"></i>
                                </el-input>
                            </el-form-item>
                        
                            <el-form-item prop="code" label="验证码"  @keydown.enter.native.prevent="phoneNext()">
                                <el-input size="normal" v-model="resetForm.code" auto-complete="off" placeholder="请输入短信验证码">
                                    <!-- <i slot="prefix" class="el-icon-lock"> </i> -->
                                    <el-button slot="suffix" @click="getPhoneMsg" type="primary" :disabled="canClick" class="sendBtn">
                                        {{btnText}}
                                    </el-button>
                                </el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button size="normal" type="primary" style="width: 100%;" @click="phoneNext()">确认</el-button>
                            </el-form-item>
                            
                        <!-- </el-form> 
                            <el-form-item  prop="tel" label="">
                                <span class="textAlign">
                                    手机号：
                                </span>
                                :readonly="!editTel":只读
                                @blur:失去焦点事件
                                <el-input v-model="resetForm.tel" type="text"  :readonly="!editTel" 
                                id="edit" >
                                    <el-link :underline="false" class="edit" slot="suffix" @click="isEdit">{{text}}</el-link>
                                </el-input>
                                <el-input v-if="editTel" v-model="resetForm.tel" type="text" :readonly="false" >
                                    <span class="unedit" slot="suffix">完成</span>
                                </el-input>
                            
                            </el-form-item>
                        </el-form> -->
                    </div>
                    <div v-if="active=='2'" class="stepItem">
                            <el-form-item prop="newPassword" label="新密码" @keydown.enter.native.prevent="dataFormSubmit()">
                                <el-input v-model="resetForm.newPassword"  show-password type="password" placeholder="6-16位大小写字母+数字组合">
                                </el-input>
                            </el-form-item>
                            <el-form-item  label="确认密码" prop="comfirmPassword" @keydown.enter.native.prevent="dataFormSubmit()" >
                                <el-input v-model="resetForm.comfirmPassword"  show-password type="password"  placeholder="请输入确认密码">
                                </el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary"  style="width: 100%; " @click="dataFormSubmit()">确认</el-button>
                            </el-form-item>
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
import SliderVerifyCode from '@/components/SliderVerifyCode.vue';
import servicesApi from '@/services/servicesApi';
import { debounce } from 'lodash'; //引入防抖
import storageService from '@/store/storage';
import { isMobile } from '@/utils/validate';
import { clearLoginInfo } from '@/utils';
export default {
    name: 'forget-password',
    data() {
        let validateAccount = (rules, value, callback) => {
            if (/[\u4E00-\u9FA5]/g.test(value)) {
                callback(new Error('账户名称不能输入汉字!'));
            } 
            // else if (/^[0-9]+$/g.test(value)) {
            //     callback(new Error('账户名称不能输入纯数字!'));
            // } 
            else {
                callback();
            }

        }
        let validateComfirmPassword = (rule, value, callback) => {
            if (this.resetForm.newPassword !== value) {
                callback(new Error('两次输入密码不一致'))
            } else {
                callback()
            }
        }
        let validatePhone = (rule, value, callback) => {
            if (!isMobile(value)) {
                callback(new Error('请输入正确的手机号码'));
            } else {
                callback();
            }
        }
        return {
            islock: false,
            text: '修改',
            editTel: false,
            btnText: '发送验证码',
            canClick: false,
            totalTime: 30,
            loginTime: 5,
            active: 0,
            phone: '',  //用户账号绑定的手机号
            resetForm: {
                newPassword: '',
                comfirmPassword: '',
                account: '',
                phone: '', //15583772258
                code: '',
                model: '',
            },
            resetFormRules: {
                phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: validatePhone, trigger: 'blur' }],
                code: [  { required: true, message: '请输入验证码', trigger: 'blur' }, ],
                account: [ { required: true, message: '请您的输入账号', trigger: 'blur' }, { min: 1, max: 15, message: '账号长度为1-15,请重新输入', trigger: 'blur' }, { validator: validateAccount, trigger: 'blur' }
                ],
                newPassword: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },  { min: 6, max: 16, message: '长度在6-16位之间', trigger: 'blur' },  { pattern: new RegExp('^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,16}$'), message: '密码为6-16位大小写字母+数字组合', trigger: 'blur' }
                ],
                comfirmPassword: [
                    { required: true, message: '请输入确认密码', trigger: 'blur' },
                    { validator: validateComfirmPassword, trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在6-16位之间', trigger: 'blur' },
                    { pattern: new RegExp('^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,16}$'), message: '密码为6-16位大小写字母+数字组合', trigger: 'blur' }
                ],
            },
        }
    },
    components: {
        SliderVerifyCode
    },
    mounted() {
        // this.getSecurityQuestion();
        // // console.log(this.$route.params.account)
        //路由接受参数
    },
    watch: {
        active(val) { // 函数名是要监听的属性
            // 重置表单，清空校验信息
            // console.log('监听的值=%s', val)
            this.$nextTick(() => {
                //  延时到下一帧才开始，也就是页面刚刚渲染结束！！
                this.$refs.resetForm.clearValidate()
            })
        }
    },
    methods: {
        dataFormSubmit: debounce(function() {
            this.$refs['resetForm'].validate((valid) => {
                if (!valid) { return false }
                servicesApi.resetPwd(this.resetForm).then(res => {
                    if (res.data.code !== 200) {
                        return this.$message.error(res.data.msg)
                    }
                    this.$message({
                        message: '密码修改成功,请登录',
                        type: 'success',
                        duration: 1000,
                        onClose: () => {
                            clearLoginInfo()
                            this.$router.replace({ name: 'login' })
                        }
                    })
                }).catch(() => { })
            })
        }, 1000, { 'leading': true, 'trailing': false }),
        phoneNext: debounce(function() { //手机验证下一步
            //对部分表单字段进行校验的方法	Function(props: array | string, callback: Function(errorMessage: string))
            this.$refs.resetForm.validateField('code', (valid) => {
                // console.log(valid)
                if (valid == '') { // valid 是校验信息 校验成功的校验信息为空字符串''
                    // this.active++
                    servicesApi.phoneLogin(this.resetForm).then(res => {
                        let code = res.data.code
                        let msg = res.data.msg
                        if (code === 200||code==201) { //鉴权成功
                            let Token = res.data.data.csrfToken;
                            let userId = res.data.data.userId;
                            //存入userId
                            storageService.setAccountId(userId)
                            // console.log('登录用户的id=%s', userId)
                            //存入token
                            // console.log('token=%s', Token)
                            storageService.setToken(Token)
                            //注意如果设置了路由守卫，要先存token再跳转页面，顺序一定不能反
                            this.active++
                            // this.$router.replace({ name: 'home', params: { hasLogin: true } })
                        } else {
                            return this.$message.error(msg)
                        }
                    })
                }
            })
        }, 1000, { 'leading': true, 'trailing': false }),
        getPhoneMsg() { //发送短信验证码
            //对部分表单字段进行校验的方法	Function(props: array | string, callback: Function(errorMessage: string))
            this.$refs.resetForm.validateField('phone', (valid) => {
                // console.log(valid)
                if (valid == '') { // valid 是校验信息 校验成功的校验信息为空字符串''
                    this.btnText = '正在发送...'
                    servicesApi.getCode(this.resetForm.phone).then(res => {
                        if (this.canClick) return
                        this.canClick = true
                        this.btnText = this.totalTime + 's后重新发送'
                        let clock = window.setInterval(() => {
                            this.totalTime--
                            this.btnText = this.totalTime + 's后重新发送'
                            if (this.totalTime < 0) {
                                window.clearInterval(clock)
                                this.btnText = '重新发送验证码'
                                this.totalTime = 30
                                this.canClick = false
                            }
                        }, 1000)
                        let code = res.data.code
                        if (code === 200) {
                            this.$message.success('短信发送成功，请注意查看');
                        } else {
                            this.$message.error('短信发送失败，请稍后重试');
                        }
                    })
                }
            });
            
        },
        toLogin() {
            this.$router.push({ path: '/login' })
        },
        blurEvent() {
            // this.editTel = false
            // this.text = '修改'
        }, 
        isEdit() { //修改手机号
            this.editTel = !this.editTel
            // console.log(this.editTel)
            // this.text = this.editTel ? '完成' : '修改'
            let edit = document.getElementById('edit')
            let val =edit.value
            // console.log(val)
            if (this.editTel) {
                edit.focus()
                edit.setSelectionRange(0, val.length)
            }
            
            // edit.contentEditable=true
        }, 
        next() {
            if (this.active++ > 2) this.active = 0;
        },
        checkAcount(val) { //校验账户
            let accountValid = false
            this.$refs.resetForm.validateField('account', (valid) => {
                // console.log(valid)
                if (valid == '') { //校验成功的校验信息为空字符串''
                    // valid 是校验信息
                    accountValid = true
                }
            });//对部分表单字段进行校验的方法	Function(props: array | string, callback: Function(errorMessage: string))
            // console.log(accountValid)
            if (val && this.resetForm.account != '' && accountValid) {
                // console.log('用户名=%s', this.resetForm.account)
                servicesApi.checkUsername(this.resetForm.account).then(res => {
                    if (res.data.code!==200) {
                        this.$message.error(res.data.msg)
                        this.islock = true
                        setTimeout(() => {
                            this.islock = false
                        }, 0.2)
                        return 
                    }
                    this.active++
                    // this.resetForm.phone = res.data.data
                    this.phone = res.data.data || ''

                })
                
            } else {
                this.islock=true
                // this.$on('change', (val)=>{//组件通信-接受
                //     // console.log(val)
                //     if(val.defalt){
                //         this.active++
                //     }
                // });
                setTimeout(() => { 
                    this.islock = false
                }, 0.1)
                //通过 v-show 和 setTimeout 刷新组件
                // this.$message.error('请输入您的账号')
            }
        },

    }
}
</script>
<style scoped>
.el-upload__tip{
    margin: 10px;
    color: #000;
    text-align: center;
}
.goback{
    margin: 20px;
    padding: 20px;
}
.stepItem{
    width: 50%;
    margin: 0 auto;
    padding: 20px;
    /* background-color: aquamarine; */
    
}

.step{
    margin-bottom: 50px;
}
.sendBtn{
    border-radius: 30px;
    width:fit-content;
}
.page-container {
    padding: 20px 40px;
    width: 100%;
    /* justify-content: center; */
    height: 100vh;
    background-color: #ffffff;
    /* background-image: url('@/assets/img/login_bg.jpg'); */
}
.main{
    width: 80%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    position: relative;
    margin: 20px;
    height:92%;
    left: 20%;
}


.content {
    /* padding: 30px 90px; */
    box-sizing: border-box;
}
</style>
